import config from "./config.js";
import st from "./showtoast.js";
import stoarge from "./stoarge.js";
import filters from "./filters.js";

const HTTP = config.apiURL + "api/";

/**
 * get请求
 */
export const get = (url, data = {}) => {
	return request(url, "GET", data);
};
/**
 * post请求
 */
export const post = (url, data = {}) => {
	return request(url, "POST", data);
};

/**
 * 网络请求
 * @param {String} url 请求地址
 * @param {'GET'|'POST'} method 请求方式
 * @param {Object} data 请求参数
 */
const request = (url, method, data) => {
	uni.showLoading({
		title: "请求中",
		mask: true,
	});
	return new Promise((resolve, reject) => {
		let token = stoarge.getToken();
		uni.request({
			url: HTTP + url,
			method,
			data,
			header: {
				"Content-Type": "application/json",
				token,
			},
			success: (res) => {
				uni.hideLoading();
				uni.stopPullDownRefresh();
				let model = res.data;
				if (model.code === 1) {
					resolve(model);
				} else if (model.code === -100) {
					if (stoarge.getLoginType() !== 1) {
						stoarge.setLoginType()
						
						st.show("登录过期，请重新登录", () => {
							stoarge.logoutClearInfo()
							filters.isLogin()
						})
					}
				} else {
					st.show(model.msg);
					reject(model);
				}
			},
			fail: (res) => {
				uni.hideLoading();
				uni.stopPullDownRefresh();
				st.show("网络请求失败，请检查网络连接或稍后重试");
			},
		});
	});
};

export const upload = (file) => {
	uni.showLoading({
		title: "上传中",
		mask: true,
	});
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: HTTP + "common/upload",
			filePath: file,
			name: "file",
			header: {
				"Content-Type": "multipart/form-data",
			},
			success: (res) => {
				uni.hideLoading();
				if (res.errMsg === "uploadFile:ok") {
					let model = JSON.parse(res.data);
					if (model.code === 1) {
						resolve(model);
					} else {
						st.show(model.msg);
						reject(model);
					}
				}
			},
			fail: (res) => {
				uni.hideLoading();
				st.show("上传失败，请检查网络连接或稍后重试");
			},
		});
	});
};

export default {
	get,
	post,
	upload,
};
